<?php
App::uses('AppController', 'Controller');
/**
 * Groups Controller
 *
 * @property Group $Group
 */
class GroupsController extends AppController {

	function admin_index() {
		$groupsTreeList = $this->Group->generateTreeList(null, null, null, '---');
		$groups = $this->Group->find('all');
		$this->set(compact('groups', 'groupsTreeList'));
	}

    function admin_add() {
        if($this->request->isPost()) {
            $inserted = array();
            $data = $this->request->data;
            if(!empty($this->request->data['Group']['name']) && is_array($this->request->data['Group']['name'])) {
                foreach($this->request->data['Group']['name'] AS $name) {
                    if(!empty($name)) {
                        $data['Group']['name'] = $name;
                        $this->Group->create();
                        $this->Group->save($data);
                        array_push($inserted, $this->Group->id);
                    }
                }
            }
            if(count($inserted) == 1) {
                return $this->redirect('/groups/add/' . $inserted[0]);
            } else if(count($inserted) >= 1) {
                $redirect = '/groups/access/' . $inserted[0] . ((count($inserted) > 1) ? '/' .implode(',', $inserted) : '');
                return $this->redirect($redirect);
            }
        }

        $groups = $this->Group->generateTreeList(null, null, null, '---');
        $this->set(compact('groups'));
    }

    function admin_access($group = 0, $groups = '') {
        $groups = $this->Group->find('list',
            array('conditions' => array(
                'Group.id' => explode(',', $groups)
            )
        ));

        $group = $this->Group->findById($group);
        debug($group);
        debug($groups);

        $this->set(compact($groups));
    }
}
